var mongoose = require('mongoose');

var User=require('../models/user.models');

exports.create = function(req,res,next){
       const user = new User(req.body);//从req.body里你获取参数对象
        


        user.save()
            .then(data=>{
                res.json(data)
            })
        
}


exports.get=function(req,res,next){
	var id=	req.params.id;
	User.findById(id,function(err,data){
		res.json(data);
	})
}

exports.update=function(req,res,next){
	const id=	req.params.id;
	
	
	User .findByIdAndUpdate(id, {$set:req.body},{new:false})
	.then(data=>{
		res.json(data)
	})
}
exports.remove=function(req,res,next){
	const id=	req.params.id;
	
	User.findByIdAndRemove(id, function(err,data){
		res.json(data)
	})
	
}


exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.rows) ? req.body.rows : 10;
	//console.log(parseInt(limit))
    var queryCondition = {};
    var name;
    if( req.body.name && req.body.name.trim().length>0 ){
        name = req.body.name;
        queryCondition = {"name":new RegExp(name,'i')}
    }

    User.paginate(queryCondition, {sort:{_id:-1}, page:page, limit: parseInt(limit)}, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
        
    });
}


exports.deletes = function(req,res,next){
	var ids = req.body.ids;
	console.log(ids)
	if(ids.length>0){
		
		User.remove({_id: {$in: ids.split(',')}})
		.then(data=>{
			res.json({"msg":"deletes success","status":200});
		})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
}

//exports.list = function(req,res,next){
//  var page = (req.query.page) ? req.query.page : 1;
//  var limit = (req.query.rows) ? req.query.rows : 10;
//
//  var queryCondition = {};
//  var name;
//  if( req.query.name && req.query.title.trim().length>0 ){
//      name = req.query.title;
//      queryCondition = {"name":new RegExp(name,'i')}
//  }
//  Users.paginate(queryCondition, {sort:{_id: -1}, page: page, limit: parseInt(limit)}, function(err, result) {
//      result.rows = result.docs;
//      delete result.docs;
//      res.json(result);
//  });
//}

//exports.delects = function(req,res,next){
//	
//}